package com.ly.common.business.util;

import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luoyana
 * @version V1.0
 * @ClassName DateUtil
 * @description
 * @update 2023/3/13
 */
@Slf4j
public class DateUtil {

    private static ThreadLocal<Map<String,DateFormat>> localFormat = new ThreadLocal<Map<String, DateFormat>>(){
        @Override
        protected Map<String,DateFormat> initialValue(){
            Map formatMap = new HashMap();
            formatMap.put("yyyy-MM-dd",new SimpleDateFormat("yyyy-MM-dd"));
            formatMap.put("HH-mm-ss",new SimpleDateFormat("HH-mm-ss"));
            formatMap.put("yyyy-MM-dd HH:mm:ss",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            formatMap.put("yyyy-MM-dd HH:mm:ss.SSS",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
            formatMap.put("yyyyMMdd HH:mm:ss.SSS",new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS"));
            formatMap.put("yyyyMMdd",new SimpleDateFormat("yyyyMMdd"));
            formatMap.put("HHmmss",new SimpleDateFormat("HHmmss"));
            formatMap.put("yyyyMMddHHmmss",new SimpleDateFormat("yyyyMMddHHmmss"));
            formatMap.put("yyyyMMddHHmmssSSS",new SimpleDateFormat("yyyyMMddHHmmssSSS"));
            formatMap.put("yyyyMMdd HH:mm:ss",new SimpleDateFormat("yyyyMMdd HH:mm:ss"));
            return formatMap;
        }
    };

    public static DateFormat getDateFormat(String pattern){
        if(localFormat.get().containsKey(pattern)){
            return localFormat.get().get(pattern);
        }
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        localFormat.get().put(pattern,dateFormat);
        return dateFormat;
    }

    public static Date parseString(String source,String pattern) throws ParseException {
        if(BusiUtil.isNull(source)){
            return null;
        }
        Date date = null;
        if(null == pattern || "".equals(pattern)){
            pattern = "yyyyMMdd";
        }

        try {
            date = getDateFormat(pattern).parse(source);
        }catch (Exception e){
            log.warn("{},{}",e.getMessage(),e);
            throw e;
        }
        return date;
    }

    public static String getDateTime(String pattern){
        return getDateTime(new Date(),pattern);
    }

    public static String getDateTime(Date date, String pattern){
        if(null == pattern || "".equals(pattern)){
            pattern = "yyyyMMdd HH:mm:ss";
        }
        return getDateFormat(pattern).format(date);
    }
}
